# user_dao.py
from sqlalchemy.orm import Session, joinedload
from ..do.user_do import UserModel


def getUser(db: Session, user_id: str):
    return db.query(UserModel).options(joinedload(UserModel.roles)).filter(UserModel.id == user_id).first()


def getUserByUsername(db: Session, username: str):
    return db.query(UserModel).options(joinedload(UserModel.roles)).filter(UserModel.username == username).first()


def getUsers(db: Session, skip: int = 0, limit: int = 100):
    return db.query(UserModel).offset(skip).limit(limit).all()


def createUser(db: Session, user):
    userModel = UserModel(**user)
    db.add(userModel)
    db.commit()
    db.refresh(userModel)
    return userModel


def updateUser(db: Session, user_id: str, user):
    userModel = getUser(db, user_id)
    if userModel is None:
        return None
    for key, value in user.items():
        setattr(userModel, key, value)
    db.commit()
    db.refresh(userModel)
    return userModel


def deleteUser(db: Session, user_id: str):
    userModel = getUser(db, user_id)
    if userModel is None:
        return False
    db.delete(userModel)
    db.commit()
    return True

from sqlalchemy import or_

def searchUsers(db: Session, keyword: str = None, skip: int = 0, limit: int = 100, sort_by: str = "username", sort_order: str = "asc", status: str = None):
    query = db.query(UserModel).options(joinedload(UserModel.roles))

    if keyword:
        query = query.filter(or_(
            UserModel.username.ilike(f"%{keyword}%"),
            UserModel.email.ilike(f"%{keyword}%")
        ))

    if status:
        # Assuming UserModel has an 'is_active' field or similar for status
        if status == "active":
            query = query.filter(UserModel.is_active == True)
        elif status == "inactive":
            query = query.filter(UserModel.is_active == False)
        # Add more status handling if needed

    # Sorting
    if sort_order == "asc":
        query = query.order_by(getattr(UserModel, sort_by).asc())
    else:
        query = query.order_by(getattr(UserModel, sort_by).desc())

    return query.offset(skip).limit(limit).all()
